<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  发布订阅模式---一对多关系

  <script>
    // 案例：售楼处发布买房公告
    /**
     * 1.主题：售楼处
     * 2.缓存列表
     * 3.当事件触发的时候（状态发生变化），依次执行回调函数
     * */
    /* 
        var salesOffices = {};
        salesOffices.clientList = []

        salesOffices.listen = function(fn) {
          this.clientList.push(fn)
        }
        salesOffices.trigger = function() {
          for (let i = 0;i < this.clientList.length;i++) {
            this.clientList[i].apply(this, arguments)
          }
        }

        salesOffices.listen(function(price, squareMeter) {
          console.log("价格"+ price);
          console.log("面积"+squareMeter);
        }) // zhangsan

        salesOffices.listen(function(price, squareMeter) {
          console.log("价格"+ price);
          console.log("面积"+squareMeter);
        }) // lisi

        salesOffices.listen(function(price, squareMeter) {
          console.log("价格"+ price);
          console.log("面积"+squareMeter);
        }) // lisi


        // 通知订阅者
        salesOffices.trigger(1000, '88')
        salesOffices.trigger(1000, '108')
         */



    // 修改让订阅者只接受想要的信息
    // 例如zhangsan 只对88房子感兴趣
    var salesOffices = {};
    salesOffices.clientList = [] // [square88:[], square108:[]]

    salesOffices.listen = function (key, fn) {
      if (!this.clientList[key]) {
        this.clientList[key] = []
      }
      this.clientList[key].push(fn)
    }
    salesOffices.trigger = function () {
      let key = Array.prototype.shift.call(arguments),
          fns = this.clientList[key];
      
      for (let i = 0; i < fns.length; i++) {
        fns[i].apply(this, arguments)
      }
    }

    salesOffices.listen('square88',function (price, squareMeter) {
      console.log("价格" + price);
      console.log("面积" + squareMeter);
    }) // zhangsan

    salesOffices.listen('square88', function (price, squareMeter) {
      console.log("价格" + price);
      console.log("面积" + squareMeter);
    }) // lisi

    salesOffices.listen('square108',function (price, squareMeter) {
      console.log("价格" + price);
      console.log("面积" + squareMeter);
    }) // lisi


    // 通知订阅者
    // salesOffices.trigger('square88', 1000, '88')
    salesOffices.trigger('square108', 1000, '108')
  </script>
</body>

</html>